package controller

import (
	"strings"

	"github.com/kataras/iris"
	"github.com/kataras/iris/sessions"

	"im/common"
	"im/dao"
	"im/model"
	"im/requests"
	"im/responses"
	"im/service"
)

type UsersController struct {
	Session *sessions.Session
	Ctx     iris.Context
	Base
}

// swagger:route GET /users users get-users
// 获取用户信息
//
// 获取用户基本信息
//   Security:
//   - jwt_key:
//   Responses:
//     200: GetUsers
func (c *UsersController) Get() {
	var (
		userToken = model.Users{}
		user      = &model.Users{}
	)
	userToken = c.Ctx.Values().Get("user").(model.Users)

	user = dao.NewUsersDao().Info(userToken.Id)
	c.SendSmile(user.UsersVisually)
	return
}

// swagger:route GET /users/others users get-users-others
// 获取其他用户基本信息
//
// 获取其他用户基本信息
//   Security:
//   - jwt_key:
//   Responses:
//     200: GetUserWithFriendStatus
func (c *UsersController) GetOthers() {
	var resp = []responses.GetUserWithFriendStatus{}
	var user = c.Ctx.Values().Get("user").(model.Users)
	userIdsStr := c.Ctx.URLParam("user_ids")
	userIdsStrList := strings.Split(userIdsStr, ",")
	userIdList := common.StringSliceToIntSlice(userIdsStrList)
	mvs, err := dao.NewUsersDao().GetListByUserIds(userIdList)
	if err != nil {
		c.SendCry(err)
		return
	}
	friendMap, err := service.NewUsersFriends().GetFriendStatus(user.Id, userIdList...)
	for _, mv := range mvs {
		status := 0
		if st, ok := friendMap[mv.Id]; ok {
			status = st
		}
		resp = append(resp, responses.GetUserWithFriendStatus{
			UsersVisually: mv,
			FriendStatus:  responses.FriendStatus{FriendStatus:status},
		})
	}
	c.SendSmile(resp)
	return
}

// swagger:route PUT /users users put-users
// 更新用户信息
//
// 更新用户基本信息
//   Security:
//   - jwt_key:
//   Responses:
//     200: EmptyResponse
func (c *UsersController) Put() {
	var (
		user  = c.Ctx.Values().Get("user").(model.Users)
		param = requests.UsersPutParams{}
		_     = c.Ctx.ReadJSON(&param)
	)
	err := service.NewUserService().UpdateById(user, param)
	if err != nil {
		c.SendCry(err)
		return
	}
	c.SendSmile(nil)
}
